<template>
  <a-modal ref="dialogDataDetailRef" v-model:open="dialogVisible" title="查看流程数据" @cancel="handleClose()" width="60%">
    <div style="padding: 0px 10px; height: 60vh; overflow-y: scroll">
      <a-tabs v-model:activeKey="activeName">
        <a-tab-pane key="json" tab="json">
          <vue-json-pretty :data="graphData.json" />
        </a-tab-pane>
        <a-tab-pane key="xml" tab="xml">
          <pre style="text-align: left">{{ xml }}</pre>
        </a-tab-pane>
      </a-tabs>
    </div>
    <template #footer>
      <a-button type="primary" class="m-flow-btn-copy" :data-clipboard-text="copyJsonContent">复制JSON</a-button>
      <a-button type="primary" class="m-flow-btn-copy" :data-clipboard-text="xml">复制XML</a-button>
    </template>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, defineExpose, computed, unref, onBeforeUnmount } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import VueJsonPretty from 'vue-json-pretty';
  import 'vue-json-pretty/lib/styles.css';
  import Clipboard from 'clipboard';
  const { createMessage } = useMessage();
  const dialogDataDetailRef = ref();
  const dialogVisible = ref(false);
  const activeName = ref('json');
  const graphData = ref({} as any);
  const clipboard = ref(null as any);

  const xml = computed(() => {
    return unref(graphData)?.xml;
  });

  const copyJsonContent = computed(() => {
    return JSON.stringify(unref(graphData)?.json, null, 2);
  });

  const show = (data: any) => {
    dialogVisible.value = true;
    graphData.value = data;
    handleOpened();
  };

  const handleOpened = () => {
    clipboard.value = new Clipboard('.m-flow-btn-copy');
    clipboard.value.on('success', (e: any) => {
      createMessage.success('复制成功');
      e.clearSelection();
    });
    clipboard.value.on('error', (e: any) => {
      createMessage.error('复制失败');
    });
  };

  const handleClose = () => {
    graphData.value = '';
    dialogVisible.value = false;
    if (clipboard.value) {
      clipboard.value.destroy();
    }
  };

  onBeforeUnmount(() => {
    if (clipboard.value) {
      clipboard.value.destroy();
    }
  });

  defineExpose({
    show,
  });
</script>
<style lang="less" scoped></style>
